package druid.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    public static DataSource ds;

    static {
        Properties properties = new Properties();
        /**
         *  利用反射获取类加载器，以此来得到加载项目中的其他文件
         */
        InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        try{
            properties.load(resourceAsStream);
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if (resourceAsStream != null){
                try{
                    resourceAsStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static DataSource getDataSource(){
        return ds;
    }

    /**
     * 从连接池中获取一个数据库的连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }

    public static void close(ResultSet set, Connection connection, Statement statement){
        if (set!=null){
            try{
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            set=null;
        }
        if (connection!=null){
            try{
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connection=null;
        }
        if (statement!=null){
            try{
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            statement=null;
        }
    }
}
